package com.qingcloud.adminbackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.exception.WmCommonException;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.entity.robot.BZProjectInfoResponseBean;
import com.qingcloud.adminbackend.entity.robot.RobotDto;
import com.qingcloud.adminbackend.entity.robot.RobotInfo;
import com.qingcloud.adminbackend.entity.robot.RobotProject;
import com.qingcloud.adminbackend.mapper.ITdRobotMapper;
import com.qingcloud.adminbackend.mapper.ITdRobotProjectMapper;
import com.qingcloud.adminbackend.mapper.SysCommonConfigMapper;
import com.qingcloud.adminbackend.service.IRobotService;
import com.qingcloud.adminbackend.utils.OKHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 机器人基础信心维护
 * </p>
 *
 * @author zhoujun
 * @since 2021-10-23
 */
@Service
@Slf4j
public class RobotServiceImpl implements IRobotService {
    //机器人产品编码
    public static final String robotProduct="WM-ROBOT-A100";
    public static final String ROBOT_COMMON_CONFIG_KEY = "wmiot_command_url";//机器人设备参数下发url地址

    @Resource
    private ITdRobotProjectMapper robotProjectMapper;

    @Resource
    private ITdRobotMapper robotMapper;

    @Resource
    private SysCommonConfigMapper sysCommonConfigMapper;

    @Override
    @Transactional
    public int delectRobot(String serialNumber){
        QueryWrapper<RobotDto> queryWrapper=new QueryWrapper();
        queryWrapper.eq("serial_number",serialNumber);
        RobotDto robotDto= robotMapper.selectOne(queryWrapper);
        if(null==robotDto){
            throw new WmCommonException("未找到机器人信息");
        }
        robotMapper.delete(queryWrapper);
        QueryWrapper<RobotProject> projectQueryWrapper=new QueryWrapper();
        projectQueryWrapper.eq("serial_number",serialNumber);
        RobotProject robotProject= robotProjectMapper.selectOne(projectQueryWrapper);
        if(null==robotProject){
            throw new WmCommonException("未找到机器人项目信息");
        }
        robotProjectMapper.delete(projectQueryWrapper);
        return 1;
    }
    @Override
    @Transactional
    public int saveRobotInfo(RobotInfo robotInfo) {
        QueryWrapper<RobotDto> queryWrapper=new QueryWrapper();
        queryWrapper.eq("serial_number",robotInfo.getSerialNumber());
        RobotDto robotDto= robotMapper.selectOne(queryWrapper);
        if(null!=robotDto){
            RobotDto dto=new RobotDto();
            BeanUtil.copyProperties(robotInfo,dto);
            QueryWrapper<RobotDto> query = new QueryWrapper<>();
            query.eq("serial_number", robotInfo.getSerialNumber());
            robotMapper.update(dto, query);
        }else{
            RobotDto dto=new RobotDto();
            BeanUtil.copyProperties(robotInfo,dto);
            dto.setEnable(1);
            robotMapper.insert(dto);
        }
        QueryWrapper<RobotProject> projectQueryWrapper=new QueryWrapper();
        projectQueryWrapper.eq("serial_number",robotInfo.getSerialNumber());
        RobotProject robotProject= robotProjectMapper.selectOne(projectQueryWrapper);
        if(null!=robotProject){
            RobotProject project=new RobotProject();
            BeanUtil.copyProperties(robotInfo,project);
            project.setId(robotProject.getId());
            robotProjectMapper.updateById(project);
        }else{
            RobotProject project=new RobotProject();
            BeanUtil.copyProperties(robotInfo,project);
            robotProjectMapper.insert(project);
        }
        return 1;
    }

    @Override
    @Transactional
    public int updataIp(List<String> serialNumbers,RobotDto dto) {
        QueryWrapper<RobotDto> query = new QueryWrapper<>();
        query.in("serial_number", serialNumbers);
        dto.setEnable(1);
        int up=robotMapper.update(dto, query);
        if(up==0){
            return up;
        }
        for(String serialNumber:serialNumbers) {
            AjaxResult<BZProjectInfoResponseBean> projectResult = projectInfo(serialNumber);
            BZProjectInfoResponseBean bean = new BZProjectInfoResponseBean();
            if (projectResult.getErroCode() == WamingConstant.SUCCESS) {
                JSONObject dataJson = JSONObject.parseObject(JSONObject.toJSONString(projectResult.getResult()));
                bean = JSONObject.parseObject(String.valueOf(dataJson.getJSONObject("data")), BZProjectInfoResponseBean.class);
            }else{
                return -1;
            }
            if(null==bean || bean.getProject_id()==null){
               return -1;
            }
            RobotProject project = new RobotProject();
            project.setProjectId(bean.getProject_id());
            QueryWrapper<RobotProject> projectQueryWrapper=new QueryWrapper();
            projectQueryWrapper.eq("serial_number",serialNumber);
            up=robotProjectMapper.update(project,projectQueryWrapper);
            if(up==1){
                //启动机器人websocket获取时时数据
                openRobotWebsocket();
            }
        }
        return up;
    }

    @Override
    public RobotProject robotProject(String serialNumber) {
        QueryWrapper<RobotProject> query = new QueryWrapper<>();
        query.in("serial_number", serialNumber);
        return robotProjectMapper.selectOne(query);
    }

    public AjaxResult projectInfo(String seriNo) {
        JSONObject param = new JSONObject();
        param.put("serial_number", seriNo);
        return sendCommand(WamingConstant.URL_ROBOT_PROJECT_INFO, param.toJSONString());
    }
    public AjaxResult openRobotWebsocket( ) {
        JSONObject param = new JSONObject();
        return sendCommand(WamingConstant.URL_ROBOT_OPEN_ROBOT_WEBSOCKET, param.toJSONString());
    }
    private AjaxResult sendCommand(String path, String param) {
        String value = sysCommonConfigMapper.findByKey(ROBOT_COMMON_CONFIG_KEY).getValue();
        String url = value + path;
        try {
            String resultStr = OKHttpUtil.httpPost(url, param);
            return JSONObject.parseObject(resultStr, AjaxResult.class);
        } catch (Exception e) {
            return new AjaxResult(WamingConstant.FAILURE, "", null);
        }
    }
}
